package com.scpii.universal.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.scpii.universal.constant.ExceptionConstants;
import com.scpii.universal.exception.GenericException;

/**
 * universalWeb
 * @author liuhj
 * 2012-7-8上午09:24:44
 * @description ajax异常拦截
 */
public class JsonExceptionHandler extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		String result = null;
		try {
			result = arg0.invoke();
			return result;
		} catch (Exception e) {
			String errorMsg = null;
			if (e instanceof GenericException) {
				GenericException genericException = (GenericException) e;
				errorMsg = e.getMessage();
				genericException.printStackTrace();
			} else {
				errorMsg = ExceptionConstants.MSG_SYSTEM_EXCEPTION;
				e.printStackTrace();
			}
			HttpServletResponse response = (HttpServletResponse) arg0
					.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
			response.setCharacterEncoding("UTF-8");
			
			PrintWriter out = response.getWriter();
			out.print(errorMsg);
			
			//记录日志
			Log log = LogFactory.getLog(arg0.getAction().getClass());
			StringBuffer logMsg = new StringBuffer(errorMsg);
			logMsg.append(e.getCause() != null ? e.getCause().getMessage() : e
					.getMessage());
			log.error(logMsg.toString(), e);
			return null;
		}
	}

}
